<template>
  <div class="c-bg-sgray c-ph22 c-pv24 c-minh100vh">
    <div class="c-pv20 c-ph24 c-br-tl20 c-br-tr20  c-bg-white c-flex-row c-aligni-center c-justify-sb">
      <div class="c-flex-row c-aligni-center">
        <img :src="userHeadImg" alt="" class="c-ww52 c-hh52 c-brp50">
        <span class="c-pl24 c-fs24"><span class="c-fc-xblack">我</span><span class="c-fc-gray c-ml10">向</span><span class="c-fc-xblack c-ml10">{{aswerInfo.name | nickNameLimitLength(5)}}</span> <span class="c-fc-gray c-ml10">{{questionCustom == 1 ? '预约' : '提问'}}</span></span>
      </div>
    </div>
    <!-- 提问详情 -->
    <div class="c-ph24 c-pt26 c-pb30 c-fs26 c-fc-xblack c-bg-white c-fw600">问题描述
      <span class="c-fc-sgray c-fs22 c-fw400" v-if="aswerInfo.quizEnable == 1 && goAsk == 1">
        <span>({{aswerInfo.textRequired == 1 ? '文字' : ''}}</span>
        <span>{{aswerInfo.textRequired == 1 && (aswerInfo.imageRequired == 1 || aswerInfo.voiceRequired == 1 || aswerInfo.videoRequired == 1) ? '、' : ''}}</span>
        <span>{{aswerInfo.imageRequired == 1 ? '图片' : ''}}</span>
        <span>{{aswerInfo.imageRequired == 1 && (aswerInfo.voiceRequired == 1 || aswerInfo.videoRequired == 1) ? '、' : ''}}</span>
        <span>{{aswerInfo.voiceRequired == 1 ? '语音' : ''}}</span>
        <span>{{aswerInfo.voiceRequired == 1 && aswerInfo.videoRequired == 1 ? '、' : ''}}</span>
        <span>{{aswerInfo.videoRequired == 1 ? '视频' : ''}}</span>必填)
      </span>
      <span v-else class="c-fc-sgray c-fs22 c-fw400">可以选择图片/语音/视频进行{{questionCustom == 1 ? '预约' : '提问'}}</span>
    </div>
    <div class="c-bg-white c-ph24 c-mb12 c-pb40 c-br-bl20 c-br-br20">
      <div class="c-bd1-f6 c-bg-sgray c-ph20 c-pv20 c-br10">
        <textarea @blur="blurInput" class="needsclick c-bg-sgray c-fc-xblack c-w100 c-bd0 c-fs24" rows="5" v-model="questionDesc" :maxlength="1024" :placeholder='chaseId ? "" : `公开${questionCustom == 1 ? "预约" : "提问"}的回答每被其他用户围观一次，你将可以获得${aswerInfo.circuseePrice}元的围观分成。72小时内未被回答，费用将自动退回。公开${questionCustom == 1 ? "预约" : "提问"}被围观的概率更高哦`'>
        </textarea>
        <div class="c-fs22 c-fc-gray c-flex-row c-aligni-end c-justify-sb">
          <div>{{questionDesc.length}}/1024</div>
          <div class="c-flex-row c-aligni-center theme-fc">
            <div class="c-p" :class="uploadAudioList.length !=0 ? 'c-pr20' : '' " >
              <div class="c-ww60 c-hh60 c-lh60 c-brp50 c-bg-white c-textAlign-c" :class="uploadImgList.length < 5?'theme-fc':'c-fc-sgray'" @click="clickChoosePic">
                <i class="iconfont c-fs32">&#xe97d;</i>
              </div>
              <input class="c-pa c-opacity0 c-p-t0 c-p-l0 c-ww36 c-hh36 c-fs10" v-if="!isWeiXin && uploadImgList.length < 5" ref="uploadImg" name="file" type="file" accept="image/*" @change="clickChoosePic($event)"/>
            </div>
            <div class="c-ww60 c-hh60 c-lh60 c-brp50 c-bg-white c-textAlign-c c-mh32" @click="clickVoiceModal" >
              <i class="iconfont c-fs32">&#xe81f;</i>
            </div>
            <div class="c-ww60 c-hh60 c-lh60 c-brp50 c-bg-white c-textAlign-c" @click="clickUploadVideo">
              <i class="iconfont c-fs32">&#xebd5;</i>
            </div>
          </div>
        </div>
      </div>
      <!-- <div class="c-fc-sblack c-fs26">可以选择图片/语音/视频进行{{questionCustom == 1 ? '预约' : '提问'}}</div> -->
      <div class="c-flex-row c-flexw-wrap">
        <div v-for="(item,index) in uploadImgList" :key="index">
          <!-- :class="index % 4 == 0 ? '':'c-ml16'" -->
          <div class="c-ww100 c-hh100 c-mt20 c-flex-row c-flex-center c-p c-mr16" >
            <div @click="delUploadImage(index)" class="iconfont upload-img-del c-fs28 c-fc-FF4A35 c-bg-white c-pz100 c-brp50">&#xe6ec;</div>
            <img @click="clickPreviewImage(item,uploadImgList)" class="c-ww100 c-hh100 c-object-fit-cover c-bd1 c-br10" :src="$addXossFilter(item)" alt="" />
          </div>
        </div>
      </div>

      <!-- 显示语音回答 -->
      <div class="c-pt30 c-fs24" v-if="uploadAudioList.length > 0">
        <div class="c-pb30 c-flex-row c-aligni-center" v-for="(item,index) in uploadAudioList" :key="index">
          <!-- <div @click="clickPlayAudio(item.url)" class="c-ww80 c-p c-maxw440 c-hh54 c-ph12 c-br10 c-bg-1BBF76 c-flex-row c-aligni-center">
            <img class="c-ww30 c-hh30 c-rotate180" v-if="playAduioSrc != item.url" src="../../../assets/i/wap/course/chat_right_play.png" alt="" />
            <img class="c-ww30 c-hh30 c-rotate180" v-else src="../../../assets/i/wap/course/chat_right_play.gif" alt="" />
            <div class="c-fs20 c-fc-white c-ws-n c-pl10">{{item.time}}"</div>
            <i @click="clickDelAudio(index)" class="iconfont c-fs28 c-fc-FF4A35" style="position: absolute;right: -11px; top: -7px;">&#xe6ec;</i>
          </div> -->
          <div v-if="item.url" :style="'width:' + (item.time * 1.5 + 150) + 'px;'" class="c-p c-mt20 c-maxw440 c-hh60 c-ph24 c-br10 c-fc-white c-bg-1BBF76 c-flex-row c-aligni-center" @click="clickPlayAudio(item.url, item.questionStatus)">
            <div v-if="playAduioSrc != item.url" class="c-flex-row c-aligni-center c-mr6">
              <span v-show="item.recordTime > 20" class="pillar-pause"></span>
              <span class="pillar-pause"></span>
              <span class="pillar-pause"></span>
              <span class="pillar-pause"></span>
              <span class="pillar-pause"></span>
              <span class="pillar-pause"></span>
              <span v-show="item.time > 10" class="pillar-pause"></span>
              <span v-show="item.time > 20" class="pillar-pause"></span>
            </div>
            <div v-else class="c-flex-row c-aligni-center c-mr6">
              <span v-show="item.time > 20" class="pillar"></span>
              <span class="pillar"></span>
              <span class="pillar"></span>
              <span class="pillar"></span>
              <span class="pillar"></span>
              <span class="pillar"></span>
              <span v-show="item.time > 10" class="pillar"></span>
              <span v-show="item.time > 20" class="pillar"></span>
            </div>
            <span class="c-flex-grow1 c-w0 c-pl10">点击播放</span>
            <span>{{item.time}}"</span>
            <i @click="clickDelAudio(index)" class="iconfont c-fs28 c-fc-FF4A35" style="position: absolute;right: -11px; top: -7px;">&#xe6ec;</i>
          </div>

        </div>
      </div>

      <!-- 显示视频回答 -->
      <div v-if="uploadVideoList.length > 0" :class="uploadAudioList.length == 0 ? 'c-pt30' : ''">
        <div class="c-flex-row c-aligni-center" v-for="(item,index) in uploadVideoList" :key="index">
          <div @click="clickShowVideo(0, 1, item.realUrl)" class="c-p c-ww320 c-hh180  c-fc-white c-flex-row c-flex-center">
            <img class="c-w100 c-br10 c-object-fit-cover" src="https://kposshzcdn.ckjr001.com/admin/material/9_material_admin/image/assets/i/wap/clockIn/video-bg1.png" alt="" />
            <i @click.stop="clickDelVideo(index)" class="iconfont c-fs28 c-fc-FF4A35" style="position: absolute;right: -11px; top: -7px; z-index: 999">&#xe6ec;</i>
          </div>

        </div>
      </div>
      <!-- <div class="c-flex-row c-aligni-center c-pv30 c-fc-gray">
        <div class="c-p" :class="uploadAudioList.length !=0 ? 'c-pr20' : '' " v-if="uploadImgList.length < 5">
          <div class="iconfont c-fs32 c-ww60 c-hh60 c-lh60 c-brp50 c-bg-sgray c-textAlign-c" @click="clickChoosePic">&#xe97d;</div>
          <input class="c-pa c-opacity0 c-p-t0 c-p-l0 c-ww36 c-hh36 c-fs10" v-if="!isWeiXin" ref="uploadImg" name="file" type="file" accept="image/*" @change="clickChoosePic($event)"/>
        </div>
        <div class="iconfont c-fs32 c-ww60 c-hh60 c-lh60 c-brp50 c-bg-sgray c-textAlign-c" :class="uploadImgList.length < 5 ? 'c-mh32' : 'c-mr32'" @click="clickVoiceModal" v-if="uploadAudioList.length==0">&#xe81f;</div>
        <div class="iconfont c-fs32 c-ww60 c-hh60 c-lh60 c-brp50 c-bg-sgray c-textAlign-c" @click="clickUploadVideo" v-if="uploadVideoList.length==0">&#xebd5;</div>
      </div> -->
      <my-loading :showLoading="showProgress" :text="uploadProgress"></my-loading>
      <input class="hide c-cursor-p needsclick" id="myUpload" type="file" accept="video/*" @change='onInputChange($event)' />
    </div>
    <div class="c-flex-row c-aligni-center c-justify-sb c-ph24 c-mv24 c-bg-white c-pv26 c-br12" v-if="!chaseId || (chaseId && chaseIsPublic != -1)">
      <div class="c-fs24 c-fc-xblack c-flex-row c-aligni-center c-fw-b">是否公开<div class="c-fs20 c-fc-sgray c-pl8">公开将展示在{{goAsk == 0 ? '问题详情页面' : questionCustom == 1 ? '预约专区' : '问答专区'}}</div></div>
      <div style="text-align:center">
        <x-switch :themeColor="$getThemeColor()" title="" v-model="ask" prevent-default @on-click="clickCheckAsk" :value-map="[0, 1]"></x-switch>
      </div>
    </div>

    <div class="c-flex-row c-aligni-center c-justify-sb c-pf c-p-b0 c-p-l0 c-p-r0 c-m-0auto c-w100 c-bg-white c-ph24 c-hh100 box-shadow" v-if="aswerInfo && aswerInfo.answerId">
      <div v-if="vipType == 2 && aswerInfo.price * 1 > 0 && !chaseId && ((aswerInfo.vipDiscountType == 1 && aswerInfo.vipDiscount < 100) || (aswerInfo.vipDiscountType == 2 && Number(aswerInfo.vipDiscountPrice) < Number(aswerInfo.price)))" class="theme-fc c-fs30">
        <span v-if="(aswerInfo.vipDiscountType == 1 && aswerInfo.vipDiscount > 0) || (aswerInfo.vipDiscountType == 2 && Number(aswerInfo.vipDiscountPrice) > 0)">{{'￥' | iosPriceFilter}}</span>
        <!-- {{((aswerInfo.vipDiscountType == 1 && Number(aswerInfo.vipDiscount * aswerInfo.price / 100) > 0) || (aswerInfo.vipDiscountType == 2 && aswerInfo.vipDiscountPrice > 0)) ? (aswerInfo.vipDiscountType == 1 ? Number(aswerInfo.vipDiscount * aswerInfo.price / 100).toFixed(2) : Number(aswerInfo.vipDiscountPrice).toFixed(2)) : '免费'}} -->
        <span v-html="$getPriceStyleHtml(Number(qaVIPPrice).toFixed(2))"></span>
      </div>
      <div v-else-if="vipType == 4 && aswerInfo.price * 1 > 0 && !chaseId && ((aswerInfo.vipDiscountType == 1 && aswerInfo.svipDiscount < 100) || (aswerInfo.vipDiscountType == 2 && Number(aswerInfo.svipDiscountPrice) < Number(aswerInfo.price)))" class="theme-fc c-fs30">
        <span v-if="(aswerInfo.vipDiscountType == 1 && aswerInfo.svipDiscount > 0) || (aswerInfo.vipDiscountType == 2 && Number(aswerInfo.svipDiscountPrice) > 0)">{{'￥' | iosPriceFilter}}</span>
        <!-- {{((aswerInfo.vipDiscountType == 1 && Number(aswerInfo.svipDiscount * aswerInfo.price / 100) > 0) || (aswerInfo.vipDiscountType == 2 && aswerInfo.svipDiscountPrice > 0)) ? (aswerInfo.vipDiscountType == 1 ? Number(aswerInfo.svipDiscount * aswerInfo.price / 100).toFixed(2) : Number(aswerInfo.svipDiscountPrice).toFixed(2)) : '免费'}} -->
        <span v-html="$getPriceStyleHtml(Number(qaSVIPPrice).toFixed(2))"></span>
      </div>
      <div v-else class="theme-fc c-fs30"><span v-if="aswerInfo.price * 1 > 0 && !chaseId">{{'￥' | iosPriceFilter}}</span>
        <span v-if="aswerInfo.price * 1 > 0 && !chaseId "v-html="$getPriceStyleHtml(Number(aswerInfo.price).toFixed(2))"></span>
        <template v-else-if="aswerInfo.freeCount * 1 > 0">免费提问{{aswerInfo.freeCount}}</template>
        <template v-else>免费</template>
        <!-- {{chaseId ? '免费' : aswerInfo.price * 1 > 0 && !chaseId ? aswerInfo.price : aswerInfo.freeCount * 1 > 0 ? `免费提问${aswerInfo.freeCount}次` : '免费'}} -->
      </div>
      <div class="c-flex-row c-aligni-center c-fs22" v-if="!chaseId" @click="clickCheckAnonymous" :class="anonymous == true ? 'theme-fc' : ''">
        <span class="iconfont c-fs30 c-lh42" :class="anonymous? 'theme-fc':'c-fc-gray'">{{anonymous ? '&#xe871;' : '&#xe872;'}}</span>
        <div class="c-fc-xblack c-ml10">匿名{{questionCustom == 1 ? '预约' : '提问'}}</div>
      </div>
      <div class="c-fc-white theme-bg c-ww280 c-hh60 c-lh60 c-fs24 c-br32 c-textAlign-c" @click="clickSubmitQuestion">{{chaseId ? '去追问' : aswerInfo.price * 1 > 0 && !chaseId ? '去支付' : '去提问'}}</div>
    </div>
    <!-- 回答语音 -->
    <open-modal :openModal='showAnswerModal' @closeModal='closeModal'>
      <div class="c-w100 c-bg-white c-flex-column c-ph24 c-pz1000 c-hh288 c-br-tr40 c-br-tl40">
        <div class="c-pt60 c-flex-column c-flex-center">
          <div @click="clickStartRecord" v-show="recordStatus == 'RECORD_START'" class="c-ww132 hh132 c-brp50 bg-green c-flex-row c-flex-center c-opacity90">
            <span class="iconfont c-fs56 c-fc-white">&#xe639;</span>
          </div>

          <img @click="clickStopRecord" v-show="recordStatus == 'RECORDING'" class="c-ww132 hh132" src="../../../assets/i/wap/course/audio_record.gif" alt="" />
          <div class="c-flex-row c-aligni-center" v-show="recordStatus == 'RECORD_END'">
            <div class="c-textAlign-c c-pr100 c-fs22" :class="isPlayTest ? 'theme-fc':'fc-lgreen'" @click="clickTryListen">
              <div class="iconfont c-fs40">&#xe993;</div>
              <div class="c-pt10">{{isWeiXin ? (isPlayTest ? '试听中':'试听') : ''}}</div>
            </div>
            <div @click="clickSentRecord" class="iconfont c-fc-white c-ww130 hh132  c-brp50 bg-green c-opacity90 c-flex-row c-flex-center c-fs80">&#xe824;</div>
            <div class="fc-lgreen c-fs22 c-pl100" @click="clickRecordAgain">
              <div class="iconfont c-fs40">&#xe994;</div>
              <div class="c-pt10">重录</div>
            </div>
          </div>

          <div v-show="recordStatus == 'RECORD_START'" class="c-fs20 c-fc-gray c-pt24">
            点击开始录音
          </div>
          <div v-show="recordStatus == 'RECORDING'" class="c-fs20 c-fc-gray c-pt24">
            录音中，还能录
            <span class="fc-lgreen">{{60-recordTime}}s</span>
          </div>
          <div v-show="recordStatus == 'RECORD_END'" class="c-fs20 c-fc-gray c-pt24">
            <span>时长</span>
            <span><span class="fc-lgreen">{{recordTime}}</span>s</span>
          </div>
        </div>
      </div>
    </open-modal>
    <video-popup :showVideo="showVideo" @clickCloseVideo="clickCloseVideo" :videoSrc="currentVideoObj.videoSrc" :m3u8Url="currentVideoObj.m3u8Url"></video-popup>
    <audio id="audio" @ended="playAudioEnd" class="c-pf c-p-l-100"></audio>
  </div>
</template>
<script>
import TcVod from "vod-js-sdk-v6";
import record from "@/utils/recorder.js";
import { utilJs, wxUtilJs } from "@/utils/common.js";
import OpenModal from "@/components/templates/common/openModal.vue";
import myLoading from "@/plugin/loading/loading.vue";
import videoPopup from "@/components/templates/common/videoPopup.vue";
import { getBindPhoneSetting } from "@/utils/checkUnBindPhone.js";
import { XSwitch } from 'ckjrweb-mp-ui/src/components/index';

let answerId = "";
let isClicking = false;
let serverIdImgArr = [];
let imgData = {};
let recordTimeCon; //录音计时控制器
let curPlayLocalId = ""; //当前播放本地音频ID
let currentLocalId = ""; //当前录制本地音频ID
let audioServerId = ""; //音频serverId
let uploader = null;
export default {
  name: "QuestionDetail",
  components: {
    OpenModal,
    myLoading,
    videoPopup,
    XSwitch
  },
  created() {
    utilJs.appShare(this);
  },
  filters: {
    formatStringTime(value) {
      if (value != undefined && value != "" && value != null) {
        return value.split(" ")[0];
      } else {
        return value;
      }
    }
  },
  computed:{
    qaVIPPrice() {
      let price = 0.00
      if (((this.aswerInfo.vipDiscountType == 1 && Number(this.aswerInfo.vipDiscount * this.aswerInfo.price / 100) > 0) || (this.aswerInfo.vipDiscountType == 2 && this.aswerInfo.vipDiscountPrice > 0))) {
        if (this.aswerInfo.vipDiscountType == 1) {
          price = Number(this.aswerInfo.vipDiscount * this.aswerInfo.price / 100).toFixed(2)
        } else {
          price = Number(this.aswerInfo.vipDiscountPrice).toFixed(2)
        }
      } else {
        price = 0.00
      }
      return price
    },
    qaSVIPPrice() {
      let price = ''
      // SVIP折扣
      if (((this.aswerInfo.vipDiscountType == 1 && Number(this.aswerInfo.svipDiscount * this.aswerInfo.price / 100) > 0) || (this.aswerInfo.vipDiscountType == 2 && this.aswerInfo.svipDiscountPrice > 0))) {
        if (this.aswerInfo.vipDiscountType == 1) {
          price = Number(this.aswerInfo.svipDiscount * this.aswerInfo.price / 100).toFixed(2)
        } else {
          price = Number(this.aswerInfo.svipDiscountPrice).toFixed(2)
        }
      } else {
        price = '0.00'
      }
      return price
    },
  },
  data() {
    return {
      theme: localStorage.getItem("colorName") || "mb5_default",
      isShowNum: JSON.parse(localStorage.getItem("questionInfo"))["isShowNum"],
      problemStatus: JSON.parse(localStorage.getItem("questionInfo")),
      companyAuth: JSON.parse(localStorage.getItem("companyAuth")),
      userHeadImg: localStorage.getItem("userHeadImg"),
      userName: localStorage.getItem("userName"),
      questionCustom: localStorage.getItem("questionCustom"), //定制阿卡西线上学院
      isPublic: 1,
      questionDesc: "",
      aswerInfo: {}, //答主信息
      anonymous: false, //是否匿名
      ask: 1,
      uploadImgList: [], //上传的图片列表
      chaseId: '',
      chaseIsPublic: 1,
      isWeiXin: true,
      isOpenIosGzhPay: utilJs.isOpenIosGzhPay('15'),
      showAnswerModal: false, //显示回答弹窗
      recordStatus: "RECORD_START", //录音状态
      recordTime: 0,
      playAduioSrc: "", //播放音频地址
      blob: '', //录音之后要上传七牛的音频文件
      qiniuInfo: {}, //录音完后的音频上传到七牛，这里是七牛的相关信息
      isPlayTest: false, //是否试听
      askType: 0, //0图文 1音频 2视频
      uploadAudioList: [], //需要上传的音频
      uploadVideoList: [], //需要上传的视频
      showVideo: false,
      videoMp4: "",
      uploadProgress: '0',
      showProgress: false,
      isChoosePic: 0,
      imgUrlListJson: "",
      isPlayingAudio: false,
      src: "", //1问答2视频3音频4图文
      courseId: "",
      imageCount: 5,
      currentVideoObj: {},
      goAsk: "", // 1 追问
      // 圈子
      circleId: "",
      circleMemberId: "",
      circleFeedsId: "",
      bindPhoneSetting: null,
      vipType: localStorage.getItem("vipType" + localStorage.getItem("userId")),
    };
  },
  methods: {
    //获取答主信息
    getAswerInfo() {
      let getUrl = `${global.apiurl}question/getRaiseQuestionInfo?answerId=${answerId}&isSkeleton=1`;
      if (this.chaseId) {
        getUrl = `${getUrl}&questionDetailId=${this.chaseId}`
      }
      utilJs.getMethod(getUrl, res => {
        this.aswerInfo = res;
        this.chaseIsPublic = res.isPublic || 1;
      }
      );
    },
    //输入框失去焦点
    blurInput(e) {
      if (navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
        setTimeout(() => {
          document.body.scrollTop = 0;
        });
      }
    },
    //点击是否公开提问
    clickCheckAsk(val) {
      this.ask = val ? 1 : 0;
    },
    //点击是否匿名
    clickCheckAnonymous() {
      this.anonymous = !this.anonymous;
    },

    //点击选择图片
    clickChoosePic(event) {
      // 图片最多上传5张
      if (this.uploadImgList.length >= 5) {
        return
      }
      this.isChoosePic = 1;
      this.askType = 0;
      if (this.isWeiXin) {
        wxUtilJs.chooseImage({
          count: this.imageCount, // 默认9
          sizeType: ["compressed"], // 可以指定是原图还是压缩图，默认二者都有
          sourceType: ["album", "camera"] // 可以指定来源是相册还是相机，默认二者都有
        }).then((localIds) => {
          localIds.reverse()
          this.$loading.show({
            text: "上传中..."
          });
          serverIdImgArr = [];
          //获取剩余能传多少张图片，若已选的图片数量大于剩余数。则只传剩余数量的图片
          let residueLength = 5 - this.uploadImgList.length;
          if (localIds.length > residueLength) {
            localIds.length = residueLength;
          }
          this.wxUploadImg(localIds, localIds.length - 1);
        });
      } else {
        utilJs.imgUpload(event.target.files, imgData, 'qa', (res) => {
          if (res.length > 0) {
            this.uploadImgList.push(res);
          }
        }, (fRes) => {});
      }
    },
    //上传图片到微信-----IOS不能一次性传多张，只好递归传
    wxUploadImg(localIds, localIdsLength) {
      wxUtilJs
        .uploadImage({ localId: localIds[localIdsLength] }, true)
        .then((res) => {
          serverIdImgArr.push(res);
          if (localIdsLength > 0) {
            this.wxUploadImg(localIds, --localIdsLength);
          } else {
            this.syncUploadPic(serverIdImgArr);
          }
        });
    },

    //上传图片到服务器
    syncUploadPic(serverIdArr) {
      utilJs.postMethod(
        global.apiurl + "question/downWxMedia",
        {
          serverId: JSON.stringify(serverIdArr),
          mediaType: 2
        },
        (res) => {
          this.$loading.hide();
          if (res.length > 0) {
            this.uploadImgList = [...this.uploadImgList, ...res];
            this.imageCount = 5 - this.uploadImgList.length;
          }
        },
        failRes => {
          this.$loading.hide();
        }
      );
    },
    //删除上传的图片
    delUploadImage(index) {
      this.uploadImgList.splice(index, 1);
      this.imageCount = 5 - this.uploadImgList.length;
    },

    //点击图片放大预览
    clickPreviewImage(imgUrl, itemImgList, questionStatus) {
      if (questionStatus == -1) {
        return;
      }
      if (!imgUrl) {
        return;
      }
      let imgUrlList = [];
      itemImgList = itemImgList.filter(item => {
        return item != 'uploadQaImg'
      })
      for (let key of itemImgList) {
        if (key) {
          imgUrlList.push(key);
        }
      }

      wxUtilJs.previewImage({
        current: imgUrl, // 当前显示图片的http链接
        urls: imgUrlList // 需要预览的图片http链接列表
      });
    },

    checkInput() {
      if (this.aswerInfo.quizEnable == 1 && this.goAsk == 1) {
        let aswerInfo = this.aswerInfo;
        let text = aswerInfo.textRequired == 1 ? '文字' : ''
        let image = aswerInfo.imageRequired == 1 ? '图片' : ''
        let voice = aswerInfo.voiceRequired == 1 ? '语音' : ''
        let video = aswerInfo.videoRequired == 1 ? '视频' : ''
        let symbol1 = aswerInfo.textRequired == 1 && (aswerInfo.imageRequired == 1 || aswerInfo.voiceRequired == 1 || aswerInfo.videoRequired == 1) ? '、' : '';
        let symbol2 = aswerInfo.imageRequired == 1 && (aswerInfo.voiceRequired == 1 || aswerInfo.videoRequired == 1) ? '、' : ''
        let symbol3 = aswerInfo.voiceRequired == 1 && aswerInfo.videoRequired == 1 ? '、' : ''
        if ((this.questionDesc == '' && (aswerInfo.textRequired == 1)) || (this.uploadImgList.length == 0 && (aswerInfo.imageRequired == 1)) || (this.uploadAudioList.length == 0 && (aswerInfo.voiceRequired == 1)) || (this.uploadVideoList == '' && (aswerInfo.videoRequired == 1))) {
          this.$showCjToast({
            text: `提问${text}${symbol1}${image}${symbol2}${voice}${symbol3}${video}必填,请完善后提问`,
            type: "warn",
          });
          return false;
        } else {
          return true;
        }
      } else {
        if (this.askType == 0 && this.questionDesc == '' && this.uploadImgList.length == 0) {
          this.$showCjToast({
            text: "请输入提问内容或上传问题图片",
            type: "warn",
          });
          return false;
        } else {
          return true;
        }
      }
    },
    clickVoiceModal() {
      // 音频只能上传1个
      if (this.uploadAudioList.length > 0) {
        return
      }
      this.askType = 1;
      this.showAnswerModal = true;
    },
    //点击开始录音
    clickStartRecord() {
      this.recordStatus = "RECORDING";
      //点击开始录音
      this.playAduioSrc = "";
      document.getElementById("audio").src = this.playAduioSrc;
      this.stopListenAudio();
      this.recordTime = 0;
      if (this.isWeiXin) {
        wxUtilJs.startRecord().then(res => {
          recordTimeCon = setInterval(() => {
            if (this.recordTime < 60) {
              this.recordTime++;
            } else {
              clearInterval(recordTimeCon);
              this.recordStatus = "RECORD_END";
            }
          }, 1000);
        }, failRes => {
          this.$showCjToast({
            text: "开启录音失败,请确认是否授权录音",
            type: "warn",
          });
          this.recordStatus = "READY";
        });

        wxUtilJs.onVoiceRecordEnd().then(localId => {
          this.recordStatus = "RECORD_END";
          clearInterval(recordTimeCon);
          currentLocalId = localId;
        });
      } else {
        record.recOpen(() => {
          record.recStart();
          recordTimeCon = setInterval(() => {
            if (this.recordTime < 60) {
              this.recordTime++;
            } else {
              clearInterval(recordTimeCon);
              this.recordStatus = "RECORD_END";
            }
          }, 1000);
          record.recVoiceRecordEnd(res => {
            this.recordStatus = "RECORD_END";
            clearInterval(recordTimeCon);
            this.blob = res;
          });
        }, () => {
          this.recordStatus = "READY";
        });
      }
    },
    closeModal() {
      if (this.recordStatus == "RECORDING") {
        return;
      }
      this.showAnswerModal = false;
    },
    //点击停止录音
    clickStopRecord() {
      this.recordStatus = "RECORD_END";
      clearInterval(recordTimeCon);
      if (this.isWeiXin) {
        wxUtilJs.stopRecord().then(localId => {
          currentLocalId = localId;
        });
      } else {
        record.recStop(res => {
          this.blob = res;
        });
      }
      if (this.recordTime < 1) {
        this.$showCjToast({
          text: "录音时间太短",
          type: "warn",
        });
        this.recordStatus = "RECORD_START";
      }
    },
    //停止试听
    stopListenAudio() {
      if (this.isPlayTest) {
        wxUtilJs.stopVoice({ localId: currentLocalId });
        this.isPlayTest = false;
      } else {
        wxUtilJs.stopVoice({ localId: curPlayLocalId });
      }
    },
    //点击发送录音
    clickSentRecord() {
      this.recordStatus = "RECORD_START";
      this.showAnswerModal = false;
      if (this.isPlayTest) {
        wxUtilJs.stopVoice({ localId: currentLocalId });
        this.isPlayTest = false;
      }
      if (this.isWeiXin) {
        wxUtilJs.uploadVoice({ localId: currentLocalId }).then(serverId => {
          audioServerId = serverId;
          this.syncUploadAudio(audioServerId);
        });
      } else {
        record.uploadAudioFile(this.blob, this.qiniuInfo, sres => {
          audioServerId = sres;
          this.syncUploadAudio(audioServerId);
        }, () => {});
      }
    },
     //点击重录
    clickRecordAgain() {
      this.recordStatus = "RECORD_START";
    },
    //点击试听
    clickTryListen() {
      if (!this.isWeiXin) {
        return;
      }
      this.isPlayTest = true;
      this.playAduioSrc = "";
      document.getElementById("audio").src = this.playAduioSrc;
      wxUtilJs.playVoice({ localId: currentLocalId });
    },
    //上传音频
    syncUploadAudio(serverId) {
      this.showAnswerModal = false;
      utilJs.postMethod(
        global.apiurl + "signCard/downWxMediaSpx",
        {
          content: serverId
        },
        (res) => {
          this.$loading.hide();
          let audioContent = {
            content: res.audioUrl,
            time: this.recordTime
          };
          this.uploadAudioSuccess(audioContent);
        },
        (failRes) => {
          this.$loading.hide();
          this.showAnswerModal = false;
        }
      );
    },
    //音频上传成功
    uploadAudioSuccess(audioContent) {
      let audioItem = {
        url: audioContent.content,
        time: audioContent.time
      };
      this.uploadAudioList.push(audioItem);
    },
    //点击开始播放音频
    clickPlayAudio(audioUrl, questionStatus) {
      if (questionStatus == -1) {
        return;
      }
      let audio = document.getElementById("audio");
      if (this.playAduioSrc == audioUrl) {
        this.playAduioSrc = "";
        document.getElementById("audio").src = this.playAduioSrc;
        return;
      }
      this.playAduioSrc = audioUrl;

      if (this.playAduioSrc && this.playAduioSrc.includes("http")) {
        document.getElementById("audio").src = this.playAduioSrc;
        audio.play();
      }
      this.isPlayingAudio = true;
    },
    //点击关闭视频
    clickCloseVideo() {
      if (this.showVideo) {
        this.showVideo = false;
      }
    },
    //监听音频播放结束执行的内容
    playAudioEnd() {
      //播放结束自动播放下一个非自己发的语音并且非已读语音
      this.playAduioSrc = "";
      document.getElementById("audio").src = this.playAduioSrc;
      this.isPlayingAudio = false;
    },
    clickUploadVideo() {
      // 视频只能上传1个
      if (this.uploadVideoList.length > 0) {
        return
      }
      this.askType = 2;
      document.getElementById("myUpload").click();
    },
    //获取得到的文件file
    onInputChange(e) {
      let inputFile = e.target.files[0];
      if (inputFile && inputFile.size > 1024 * 1024 * 1024) {
        this.$showCjToast({
          text: "视频文件大小不能超过1G",
          type: "warn",
        });
        return false;
      }
      if (inputFile) {
        this.uploadVideoToTencent(inputFile);
      }
    },
    uploadVideoToTencent(inputFile) {
      let that = this;
      this.showProgress = true;
      const tcVod = new TcVod({
        // eslint-disable-line
        getSignature: utilJs.getVideoSign
      });
      uploader = tcVod.upload({
        mediaFile: inputFile // 媒体文件（视频或音频或图片），类型为 File
      });
      uploader.on("media_progress", function (info) {
        that.uploadProgress = `上传进度:${Math.floor(info.percent * 100)}%`;
      });
      uploader
        .done()
        .then(function (result) {
          that.videoMp4 = result.video.url;
          that.showProgress = false;
          let videoInfo = {
            url: result.fileId,
            realUrl: result.video.url
          };
          that.uploadVideoList.push(videoInfo);
          let data = {
            videoId: result.fileId,
            videoMp4: result.video.url,
            videoName: inputFile.name
          };
          that.videoFirstSave(data);
          that.uploadProgress = '0';
          document.getElementById("myUpload").value = null;
        })
        .catch((err) => {
          that.showProgress = false;
          that.$showCjToast({
            text: "上传失败，请尝试重新上传",
            type: "warn",
          });
          that.uploadProgress = '0';
          document.getElementById("myUpload").value = null;
          let errorData = {
            errorMsg: JSON.stringify(err),
            errorType: "UPLOAD_VIDEO_ERROR"
          };
          utilJs.reprotError(errorData);
        });
    },
    //点击提交问题
    clickSubmitQuestion() {
      if (this.bindPhoneSetting && this.bindPhoneSetting.buyBind) {
        if (utilJs.goBindMobile()) return;
      }
      if (!this.checkInput()) {
        return;
      }
      if (isClicking) {
        return;
      }

      let that = this;
      isClicking = true;
      if (this.isChoosePic == 1) {
        //去掉图片中含有upload的item
        this.imgUrlListJson = JSON.stringify(this.uploadImgList);
      }
      utilJs.postMethod(
        global.apiurl + "question/submitQuestionDetail",
        {
          questionDetailId: this.chaseId,
          type: this.chaseId ? 2 : 1,
          answerId: answerId,
          imgUrl: this.imgUrlListJson,
          detail: this.questionDesc,
          isPublic: this.ask == 1 ? 1 : -1,
          isHidden: this.anonymous ? -1 : 1,
          serverId: audioServerId || "",
          recordTime: this.recordTime || "",
          videoId: this.uploadVideoList.length > 0 ? this.uploadVideoList[0].url : "",
          videoMp4: this.videoMp4 || "",
          src: this.src,
          courseId: this.courseId,
          circleId: this.circleId,
          circleMemberId: this.circleMemberId
        },
        res => {
          if (res.isFree == 1 || this.chaseId) {
            this.$showCjToast({
              text: "提问成功",
              type: "success",
            }).then(() => {
              let qID = that.chaseId || res.questionDetailId
              that.isClicking = false;
              if (that.circleId != "" && that.circleMemberId != "" && that.circleFeedsId != "") {
                that.$routerGo(that, "push", {
                  path: "/homePage/circle/circleDetail",
                  query: {
                    circleFeedsId: that.circleFeedsId
                  }
                })
              } else if (that.circleId != "" && that.circleMemberId) {
                that.$routerGo(that, "push", {
                  path: "/homePage/circle/circleFeed",
                  query: {
                    id: that.circleId
                  }
                })
              } else {
                that.$routerGo(that, "push", { path: `/homePage/qa/answerDetail?questionDetailId=${qID}` });
              }
            });
          } else {
            isClicking = false;
            if (!utilJs.isOpenIosGzhPay('15')) {
              this.$store.commit('updateShowVitualModal', true);
              return;
            }
            that.$routerGo(that, "push", {
              path: "/homePage/course/coursePay",
              query: {
                extId: res.questionOrderId,
                ckFrom: global.ckFrom.qa,
                cId: -1,
                circleId: this.circleId,
                circleMemberId: this.circleMemberId
              }
            });
          }
        },
        failRes => {
          isClicking = false;
        }
      );
    },
     //点击显示视频
    clickShowVideo(isReply, questionStatus, videoSrc, m3u8Url) {
      if (questionStatus == -1) {
        return;
      }
      if (this.isPlayingAudio == true) {
        this.playAudioEnd();
      }
      this.showVideo = true;
      this.currentVideoObj = {videoSrc, m3u8Url}
    },
    // 删除音频
    clickDelAudio(index) {
      if (document.getElementById("audio")) {
        this.playAduioSrc = "";
        document.getElementById("audio").src = this.playAduioSrc;
        document.getElementById("audio").pause();
      }
      this.uploadAudioList.splice(index, 1);
    },
    // 删除视频
    clickDelVideo(index) {
      this.uploadVideoList.splice(index, 1);
    },
    //保存视频
    videoFirstSave(data) {
      utilJs.postMethod(
        global.apiurl + "signCard/videoFirstSave",
        data,
        (res) => {}
      );
    },
    //分享
    wechatShare: function () {
      let questionInfo = JSON.parse(
        window.localStorage.getItem("questionInfo")
      );
      let title = questionInfo.title;
      let shareImg = questionInfo.cover;
      let shareUrl = `${window.location.href.split("#")[0]}#/homePage/qa/answerLord?src=${this.src}&courseId=${this.courseId}&refereeId=${localStorage.getItem("userId")}`;
      let shareDesc = questionInfo.describe;
      utilJs.wechatConfig(
        shareUrl,
        title,
        shareImg,
        shareDesc,
        function () { },
        true
      );
    },
    //手机端分享
    appShare() {
      let questionInfo = JSON.parse(
        window.localStorage.getItem("questionInfo")
      );
      let title = questionInfo.title;
      let shareImg = questionInfo.cover;
      let shareUrl = `${window.location.href.split("#")[0]}#/homePage/qa/answerLord?src=${this.src}&courseId=${this.courseId}&refereeId=${localStorage.getItem("userId")}`;
      let shareDesc = questionInfo.describe;
      utilJs.appShareTrue(title, shareImg, shareUrl, shareDesc);
    }
  },
  activated() {
    setDocumentTitle("发起提问");// eslint-disable-line
    if ((this.problemStatus && this.problemStatus.status == -1) || (this.companyAuth && this.companyAuth.enableQuestionModule == -1)) {
      this.$routerGo(this, "replace", {
        path: "/error/emptyPage",
        query: {
          info: "问答已下架"
        }
      });
    }
    this.isWeiXin = utilJs.isWeiXin();
    curPlayLocalId = "";
    answerId = this.$route.query.answerId;
    isClicking = false;
    this.goAsk = this.$route.query.goAsk
    this.chaseId = this.$route.query.chaseId || '';
    this.courseId = this.$route.query.courseId || '';
    this.src = this.$route.query.src;
    this.qiniuInfo = {};
    this.isShowNum = JSON.parse(localStorage.getItem("questionInfo"))["isShowNum"];
    this.isPublic = 1;
    this.questionDesc = "";
    this.aswerInfo = {}; //答主信息
    this.anonymous = false; //是否匿名
    this.ask = 1;
    this.uploadImgList = []; //上传的图片列表
    this.uploadAudioList = [];
    this.showAnswerModal = false;
    this.recordStatus = "RECORD_START";
    this.recordTime = 0;
    this.playAduioSrc = "";
    this.imageCount = 5;
    recordTimeCon = null;
    audioServerId = "";
    this.askType = 0;
    uploader = null;
    this.isPlayTest = false;
    this.uploadVideoList = [];
    this.showVideo = false;
    this.videoMp4 = "";
    this.showProgress = false;
    this.isPlayingAudio = false;
    this.isChoosePic = 0;
    this.uploadProgress = '0';
    this.imgUrlListJson = "";
    this.circleId = this.$route.query.circleId || "";
    this.circleMemberId = this.$route.query.circleMemberId || "";
    this.circleFeedsId = this.$route.query.circleFeedsId || "";
    getBindPhoneSetting(global.ckFrom.qa).then(res => {
      this.bindPhoneSetting = res;
    });
    this.getAswerInfo();
    //获取阿里云签名，除了微信浏览器以外
    if (!utilJs.isWeiXin()) {
      utilJs.getAliSign(`${global.apiurl}imageSign`, res => {
        imgData = res;
      });
      utilJs.getMethod(
        global.apiurl + "common/qiniu/uploadToken",
        (res) => {
          this.qiniuInfo.qiNiuToken = res;
        }
      );
    }
    this.wechatShare();
  },
  deactivated() {
    clearInterval(recordTimeCon);
    this.stopListenAudio();
    this.uploadImgList = [];
    this.playAduioSrc = "";
    if (document.getElementById("audio")) {
      document.getElementById("audio").src = '';
    }
    if (!this.isWeiXin && record != null) {
      record.recClose();
    }
  }
};
</script>
<style scoped>
textarea {
  resize: none;
  line-height: 0.85rem;
}
.upload-img-del {
  position: absolute;
  right: -0.35rem;
  top: -0.25rem;
}
.fc-lgreen {
  color: #1BBF76;
}
.bg-green {
  background: #1BBF76;
}
.hh132 {
  height: 3.3rem;
}
.box-shadow {
  box-shadow: 0px -5px 10px 0px rgba(0,0,0,0.02);
}
</style>
<style lang="scss" scoped>
@function pxToRem($px) {
  //$rpx为需要转换的字号
  @return $px/40 + rem;
}
@-webkit-keyframes pillarDance{
  0%{height:pxToRem(8);}
  50%{height:pxToRem(24);}
  100%{height:pxToRem(8);}
}
.pillar{
  width: 0.1rem;
  margin: 0 0.1rem;
  height: pxToRem(8);
  background: #fff;
  border-radius: 0.2rem;
  animation: pillarDance 2s infinite ease;
}
.pillar:first-child{
  animation-delay:0.5s;
}
.pillar:nth-child(2){
  animation-delay:1s;
}
.pillar:nth-child(3){
  animation-delay:1.5s;
}
.pillar:nth-child(4){
  animation-delay:2s;
}
.pillar:nth-child(5){
  animation-delay:0.5s;
}
.pillar:nth-child(6){
  animation-delay:1s;
}
.pillar:nth-child(7){
  animation-delay:1.5s;
}
.pillar:nth-child(8){
  animation-delay:2s;
}

.pillar-pause{
  width: 0.1rem;
  margin: 0 0.1rem;
  height: pxToRem(8);
  background: #fff;
  border-radius: 0.2rem;
}
.pillar-pause:nth-child(2){
  height: pxToRem(12);
}
.pillar-pause:nth-child(3){
  height: pxToRem(16);
}
.pillar-pause:nth-child(4){
  height: pxToRem(24);
}
.pillar-pause:nth-child(5){
  height: pxToRem(24);
}
.pillar-pause:nth-child(6){
  height: pxToRem(16);
}
.pillar-pause:nth-child(7){
  height: pxToRem(12);
}
.pillar-pause:nth-child(8){
  height: pxToRem(8);
}
</style>